import axios from 'axios'
import apis from './ApiUrls';
import storageUtil from './StorageUtil';

// 创建 axios 实例
const axiosInstance = axios.create({
    baseURL: apis.api_host, // 基础url
    timeout: 5000, // 请求超时时间
    // 'Content-Type': 'application/x-www-form-urlencoded',
});

// 错误处理函数
const errHandler = (error) => {
    console.log(error);
    if (!error.response) {
        // 通信异常
        return Promise.reject({
            code: 500,
            status: 'INTERNAL_SERVER_ERROR',
            msg: '通信异常',
        });
    } else {
        return Promise.reject(error.response);
    }
}

// request interceptor(请求拦截器)
axiosInstance.interceptors.request.use(config => {
    const metaData = storageUtil.get();

    if (metaData.authorization) {
        config.headers['Authorization'] = metaData.authorization // 让每个请求携带token
    }
    if (metaData.userId) {
        config.headers['UserId'] = metaData.userId
    }
    return config
}, errHandler);

// response interceptor（接收拦截器）
axiosInstance.interceptors.response.use((response) => {
    const res = response.data

    // 针对下载的处理-- 下载的时候请求type为blob- response.data为数据,结构不一致,所以出错后一定会进入500
    if (response.headers['md-file']) {
        const blob = new Blob([res], {type: response.headers['content-type']});
        const fileName = response.headers['content-disposition'].replace(/\w+; filename=(.*)/, '$1')
        let dom = document.createElement('a');
        let url = window.URL.createObjectURL(blob);
        dom.href = url;
        dom.download = decodeURI(fileName);
        dom.style.display = 'none'
        document.body.appendChild(dom);
        dom.click();
        dom.parentNode.removeChild(dom);
        window.URL.revokeObjectURL(url);
        return;
    }

    if (res.code !== 200) {

        let msg = res.msg;
        if (res.code === 500) {
            msg = "系统内部错误";
            console.log(res.msg);
        }

        if (res.code === 401) {
            msg = "禁止未经认证的访问";
        }

        if (res.code === 403) {
            msg = "似乎没有登录或者登录信息异常";
        }

        if (res.code === 408) {
            msg = "认证信息过期了~需要重新登录";
        }

        // 认证失败则清空缓存
        if (res.code === 401 || res.code === 403) {
            storageUtil.clear();
        }

        return Promise.reject({
            code: res.code,
            status: res.status,
            msg: msg,
        });
    } else {
        // 给login做特殊处理
        if (response.headers.authorization && response.headers.refreshtoken && response.headers.userid) {
            const metaData = {
                authorization: response.headers.authorization,
                refreshToken: response.headers.refreshtoken,
                userId: response.headers.userid,
                loginMills: response.headers.loginmills,
                auth: response.headers.userauth,
            }
            storageUtil.set(metaData);
        }
        return Promise.resolve(res);
    }
}, errHandler);




export default axiosInstance;
